/*
 * @Description: 元数据上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-10-26 15:23:49
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import {
  ADD_METADATA,
  DELETE_METADATA,
  EDIT_METADATA,
  INIT_QUERY,
  METADATA_LOADING,
  METADATA_LOADING_FINISH,
  QUERY_METADATA_ALL,
  SET_METADATA_LIST,
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_LEVEL
} from '../constants';
import { MetadataReducer } from '../reducers/MetadataReducer';
import {
  addMetadata,
  deleteMetadata,
  editMetadataBusinessById,
  fetchMetadata
} from '@/api/metadata';
import { SET_SELECTED_ITEM } from '@/view/system/Units/constants';
import { Modal } from 'antd';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectLevel: {},

  metadataLoading: false,
  metadataList: [],
  // 选中的表格条目
  selectItems: [],
  listQuery: {},

  // dictionaries
  duplicateList: [
    { id: 0, name: '允许', color: 'blue' },
    { id: 1, name: '不允许', color: 'red' }
  ],
  nullList: [
    { id: 0, name: '允许', color: 'blue' },
    { id: 1, name: '不允许', color: 'red' }
  ],
  deleteList: [
    { id: 0, name: '正常', color: 'blue' },
    { id: 1, name: '删除', color: 'red' }
  ],
  typeList: [
    { id: 0, name: '字符型' },
    { id: 1, name: '整型' },
    { id: 2, name: '长整型' },
    { id: 3, name: '小数型' },
    { id: 4, name: '日期型' },
    { id: 5, name: '时间型' },
    { id: 6, name: '大对象' }
  ],
  kindList: [
    { id: 0, name: '系统字段', color: 'blue' },
    { id: 1, name: '业务字段', color: 'green' }
  ]
};

const MetadataContext = createContext();

const MetadataContextProvider = (props) => {
  const [state, dispatch] = useReducer(MetadataReducer, initialState);

  const actions = {
    /**
     * @description: 表格选中的项目
     * @param {*} selectArr 选中的项目
     */
    setSelectedItem(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 设置选中的全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的层级
     */
    setSelectLevel(data) {
      dispatch({ type: SET_SELECT_LEVEL, data });
    },

    /**
     * @description: 请求级别元数据列表方法
     * @param {object} fieldQuery 请求参数
     * @return {*}
     */
    fetchMatedataFunc(coordinate) {
      dispatch({ type: METADATA_LOADING });
      const fieldQuery = {
        metadataFieldType: QUERY_METADATA_ALL,
        coordinate
      };
      fetchMetadata(fieldQuery)
        .then((res) => {
          const { data } = res;
          dispatch({ type: SET_METADATA_LIST, data });
        })
        .catch((err) => {
          console.log(err);
          dispatch({ type: SET_METADATA_LIST, data: [] });
        })
        .finally(() => {
          dispatch({ type: METADATA_LOADING_FINISH });
        });
    },

    /**
     * @description: 初始化排序列表请求条件
     * @param {object} data 修改的请求内容
     */
    initListQuery(data) {
      dispatch({ type: INIT_QUERY, data });
    },

    addMetadataFunc(field) {
      const params = {
        coordinate: {
          atCode: state.selectAT.atCode,
          atType: state.selectAT.atType,
          level: state.selectLevel.level
        },
        field
      };
      return new Promise((resolve, reject) => {
        addMetadata(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_METADATA, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    editMetadataFunc(field) {
      const params = {
        coordinate: {
          atCode: state.selectAT.atCode,
          atType: state.selectAT.atType,
          level: state.selectLevel.level
        },
        field
      };
      return new Promise((resolve, reject) => {
        editMetadataBusinessById(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_METADATA, data, id: data.id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    deleteMetadataFunc(info) {
      Modal.confirm({
        title: '删除',
        content: '确认删除该字段？',
        onOk() {
          info.atCode = state.selectAT.atCode;
          info.atType = state.selectAT.atType;
          info.level = state.selectLevel.level;
          deleteMetadata(info).then((res) => {
            const { data } = res;
            dispatch({ type: DELETE_METADATA, data, id: info.fiRecordId });
          });
        },
        onCancel() {
          console.log('del unit Cancel');
        }
      });
    }
  };

  // watch listQuery来加载列表
  useEffect(() => {
    if (state.listQuery && JSON.stringify(state.listQuery) !== '{}') {
      actions.fetchMatedataFunc(state.listQuery);
    }
  }, [state.listQuery]);

  return (
    <MetadataContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </MetadataContext.Provider>
  );
};

export const useMetadataContext = () => {
  return useContext(MetadataContext);
};

export { MetadataContext, MetadataContextProvider };
